import socket
import json
import struct



sk = socket.socket()
sk.connect(('127.0.0.1', 9000))

#下载
filename = input('>>>').strip()
dic = {'filename': filename, 'oprate': 'download'}

str_dic = json.dumps(dic)#字典转json
bdic = str_dic.encode('utf-8') #str转bytes
dic_len = len(bdic) #计算bytes长度
bytes_len = struct.pack('i', dic_len)
sk.send(bytes_len)
sk.send(bdic)

dic_len = sk.recv(4)
dic_len = struct.unpack('i', dic_len)[0]
dic = sk.recv(dic_len).decode('utf-8')
dic = json.loads(dic)

if dic['isfile']:
    with open(filename,'wb') as f:
        while dic['filesize'] > 2048:
            content = sk.recv(2048)
            f.write(content)
            dic['filesize'] -= len(content)

        else:
            content = sk.recv(dic['filesize'])
            f.write(content)

else:
    print('不存在')